//
//  JPTabBarController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/4/19.
//

#import "JPTabBarController.h"
#import "WordsViewController.h"
#import "ExamViewController.h"
#import "DiscoverViewController.h"
#import "MineViewController.h"
#import "JPNavigationController.h"
#import <AudioToolbox/AudioToolbox.h>
#import "AIViewController.h"

@interface JPTabBarController ()<UITabBarControllerDelegate>
@property(nonatomic,assign)NSInteger indexFlag;
@property(nonatomic,strong)UIView *customTabbarView;
@end

@implementation JPTabBarController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.delegate = self;
    [self createUI];
}

#pragma mark - 界面初始化
-(void)createUI{
    
    self.tabBar.tintColor = KThemeColor;
    
    self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];

    //改变tabbar 线条颜色
    CGRect rect = CGRectMake(0, 0,self.currentAvailableWidth,0.5);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context,UIColorHex(0xEEEEEE).CGColor);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [self.tabBar setShadowImage:img];



    [self setupChildVc:[[WordsViewController alloc] init] title:@"" image:@"tab_home_unsel" selectedImage:@"tab_home_sel" hiddenNavigationBar:YES];

    [self setupChildVc:[[ExamViewController alloc] init] title:@"" image:@"tab_exam_unsel" selectedImage:@"tab_exam_sel" hiddenNavigationBar:YES];
    
    [self setupChildVc:[[AIViewController alloc] init] title:@"" image:@"tab_ai_unsel" selectedImage:@"tab_ai_sel" hiddenNavigationBar:YES];

    [self setupChildVc:[[DiscoverViewController alloc] init] title:@"" image:@"tab_discover_unsel" selectedImage:@"tab_discover_sel" hiddenNavigationBar:YES];

    [self setupChildVc:[[MineViewController alloc] init] title:@"" image:@"tab_mine_unsel" selectedImage:@"tab_mine_sel" hiddenNavigationBar:YES];

    [self createTabbarUI];
    
}

- (void)createTabbarUI{
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor whiteColor];
    view.frame = self.tabBar.bounds;
    view.height = kYM_TABBAR_HEIGHT;
    view.width = self.currentAvailableWidth;
    [[UITabBar appearance] insertSubview:view atIndex:0];
    self.customTabbarView = view;
}

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

    if (isIPAD) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.customTabbarView.width = self.currentAvailableWidth;
        });
    }
}


#pragma mark - 选中某个下标
- (void)selectedtabVCWithIndex:(NSInteger)index{
    self.selectedIndex = index;
}

//初始化子控制器
- (void)setupChildVc:(UIViewController *)vc
               title:(NSString *)title
               image:(NSString *)image
       selectedImage:(NSString *)selectedImage
 hiddenNavigationBar:(BOOL)isHiddenNavBar{
    // Title Setter
    if(!isHiddenNavBar) vc.title = title;
    [vc.tabBarItem setTitle:title];

    //设置不显示文字，将title的位置设置成无限远，就看不到了
    vc.tabBarItem.titlePositionAdjustment = UIOffsetMake(0,-3);

//    NSDictionary *c_nor =  @{NSForegroundColorAttributeName:UIColorHex(0xB2B2B2),NSFontAttributeName:JPUIFontPingFangSCMedium(12)};
//    NSDictionary *c_sel =  @{NSForegroundColorAttributeName:KThemeColor,NSFontAttributeName:JPUIFontPingFangSCMedium(12)};
//    
//    [vc.tabBarItem setTitleTextAttributes:c_nor forState:UIControlStateNormal];
//    [vc.tabBarItem setTitleTextAttributes:c_sel forState:UIControlStateSelected];
    
    // Image Setter
    UIImage *img = [UIImage imageNamed:image];
    img = [img imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    vc.tabBarItem.image = img ;

    UIImage *selImage = [UIImage imageNamed:selectedImage];
    selImage = [selImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    vc.tabBarItem.selectedImage = selImage;

    
    // Add To Tabbar
    JPNavigationController*nav = [[JPNavigationController alloc] initWithRootViewController:vc];
    nav.navigationBar.hidden = isHiddenNavBar;
    [self addChildViewController:nav];
    
}

//获取当前控制器
-(UIViewController *)getCurrentVC {
    UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
    UIViewController* currentViewController = window.rootViewController;
    BOOL runLoopFind = YES;
    while (runLoopFind) {
        if (currentViewController.presentedViewController) {
            currentViewController = currentViewController.presentedViewController;
        } else {
            if ([currentViewController isKindOfClass:[UINavigationController class]]) {
                currentViewController = ((UINavigationController *)currentViewController).visibleViewController;
            } else if ([currentViewController isKindOfClass:[UITabBarController class]]) {
                currentViewController = ((UITabBarController* )currentViewController).selectedViewController;
            } else {
                break;
            }
        }
    }
    return currentViewController;
}


#pragma mark - UITabBarControllerDelegate
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item{
    NSInteger index = [self.tabBar.items indexOfObject:item];
    if (index != self.indexFlag) {
        //执行动画
        NSMutableArray *array = [NSMutableArray array];
        for (UIView *btn in self.tabBar.subviews) {
            if ([btn isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
                [array addObject:btn];
            }
        }
        
//        NSString *chatterStatus = [[NSUserDefaults standardUserDefaults]objectForKey:@"chatterStatus"];
//        if(!(chatterStatus&&[chatterStatus isEqualToString:@"0"])){
//            if (@available(iOS 10.0, *)){
//                UIImpactFeedbackGenerator *feedBackGenertor = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleHeavy];
//                [feedBackGenertor impactOccurred];
//            }else{
//                AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);//默认震动效果
//            }
//        }
        
        //添加动画
        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        animation.duration = 0.1;
        animation.repeatCount = 1;
        animation.autoreverses = YES;//完成动画后会回到执行动画之前的状态
        animation.fromValue = [NSNumber numberWithFloat:0.8];
        animation.toValue = [NSNumber numberWithFloat:1.1];
        UIView *btn = array[index];
        [[btn layer]addAnimation:animation forKey:nil];
        
        self.indexFlag = index;
        
       
    }
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    return YES;
}


@end
